import re
from users.models import User
from django.contrib.auth.backends import ModelBackend


class MyAuthenticateBackend(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        # 1,如果vue前端程序请求来的request为空(判断管理员登录）
        if not request:
            try:
                user = User.objects.get(username=username, is_superuser=True)
            except Exception as e:
                return None

            if not user.check_password(password):
                return None

            return user
        else: #前台用户登录
            try:
                # 1,先判断username是否是手机号
                if re.match(r'^1[3-9]\d{9}$', username):

                    user = User.objects.get(mobile=username)

                else:
                    # 2,然后在通过用户名查询,用户
                    user = User.objects.get(username=username)
            except User.DoesNotExist:
                return None
            if user and user.check_password(password):
                return user

